import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/5/18
 * \* Time: 18:25
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 电话号码的字母组合 {
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if(digits.length()==0){
            return combinations;
        }

        Map<Character, String> phoneMap=new HashMap<Character, String>(){
            {
                put('2', "abc");
                put('3', "def");
                put('4', "ghi");
                put('5', "jkl");
                put('6', "mno");
                put('7', "pqrs");
                put('8', "tuv");
                put('9', "wxyz");
            }
        };
        backTrack(combinations,phoneMap,digits,0,new StringBuffer());
        return combinations;
    }

    public void backTrack(List<String>combinations,Map<Character,String> phoneMap,String digits,int index,StringBuffer combination){
        if(index==digits.length()){
            combinations.add(combination.toString());
        }else{
            //获取当前数字
            char digit= digits.charAt(index);
            //获取数字对应的字母表
            String letters=phoneMap.get(digit);
            //获取字母表长度
            int letterCount=letters.length();
            for(int i=0;i<letterCount;i++){
                //添加第i个字母进来
                combination.append(letters.charAt(i));
                //添加分支
                backTrack(combinations, phoneMap, digits, index + 1, combination);
                //删除第i个字母，把当前位置留给i+1个
                combination.deleteCharAt(index);
            }
        }
    }
}